package com.xrit.sunnyday.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.xrit.sunnyday.dao.OrderSettingDao;
import com.xrit.sunnyday.exception.SunnydayException;
import com.xrit.sunnyday.pojo.OrderSetting;
import com.xrit.sunnyday.service.OrderSettingService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 预约设置
 */
@Service(interfaceClass = OrderSettingService.class)
public class OrderSettingServiceImpl implements OrderSettingService{

    @Autowired
    private OrderSettingDao orderSettingDao;

    /**
     * 批量导入
     *
     * @param orderSettingList
     */
    @Override
    public void add(List<OrderSetting> orderSettingList) throws SunnydayException {
        //1.遍历挨个取每一行
        for (OrderSetting os : orderSettingList) {
            //2.取出日期
            Date orderDate = os.getOrderDate();
            //3.拿日期查询数据表里是否存在重复重复代表医生要进行更新
            OrderSetting orderSetting = orderSettingDao.findByOrderDate(orderDate);
            //判断对应日期是否存在
            if (null != orderSetting){
                //判断数据库表已预约人数是否大于可预约人数
                if (orderSetting.getReservations()>os.getNumber()){
                    //如果大于 报错
                    throw new SunnydayException(os.getOrderDate()+"中，已预约人超出了你设置的可预约人数，如需可增加可预约人数");
                }
                //小于就更新可预约人数
                orderSettingDao.updateNumber(os);
            } else {
                //不存在
                orderSettingDao.add(os);
            }
        }
    }

    /**
     * 根据日期查询预约设置数据
     *
     * @param month
     * @return
     */
    @Override
    public List<Map<String, Integer>> getOrderSettingByMonth(String month) {
        //1.拼接开始的日期
        String startDate = month + "-01";
        //2.只传开始的日期，使用Mysql的函数 找出对应MM月的最后一天
        return orderSettingDao.getOrderSettingByMonth(startDate);
    }

    /**
     * 根据日期修改可预约人数
     * @param orderSetting
     */
    @Override
    public void editNumberByDate(OrderSetting orderSetting) {
        //1.获取前端传递过来的日期
        Date orderDate = orderSetting.getOrderDate();
        //2.通过日期判断该预约设置是否存在
        OrderSetting byOrderDate = orderSettingDao.findByOrderDate(orderDate);
        //存在
        if (null != byOrderDate) {
            //3.判断已预约人数是否大于更新的最大可预约人数 低于已预约人数不能更新 报错
            if (byOrderDate.getReservations() > orderSetting.getNumber()){
                throw new SunnydayException("最大预约人数不能小于已预约人数!");
            }
            // 4.更新最大可预约数量
            orderSettingDao.editNumberByOrderDate(orderSetting);
        } else {
            //不存在 添加预约设置信息
            orderSettingDao.add(orderSetting);
        }
    }
}
